/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

import sagroup.dracots.DracoTS;
import sagroup.dracots.FlatShareTuple;

import sagroup.dracots.ShareTuple;
import sagroup.dracots.TupleType;
import sagroup.util.Util;

import lime2.Location;
import lime2.TupleID;

/**
 * @author Xing Jiankuan
 * 
 */
public class ReadAgent extends AbstractAgent {

	private long meaninterval;
	private Location remote;
	private TupleType type;
	private volatile boolean timesup = false;
//	private double prob = 0;
	private int opCountR = 0; //remote operation count
	
	private int opCountL = 0; //local operation count

	private DracoTS dts = null;

	private long usedTotalTimeR = 0L; //remote operation time
	
	private long usedTotalTimeL = 0L;

	private Logger LOG = Logger.getLogger(this.getClass().getName());

	private HashSet<TupleID> haveRead = new HashSet<TupleID>();
	private HashSet<TupleID> unRead = new HashSet<TupleID>();

	int icount = 0;

	/**
	 * 
	 */
	public ReadAgent(HashMap<String, String> params,Long[][] array) {
	 super(params.get("agentname"),Long.valueOf(params.get("meaninterval")),
			 Long.valueOf(params.get("prob")), array);
		try {
			this.type = new TupleType(params.get("typename"));
			this.meaninterval = Long.valueOf(params.get("meaninterval"));
			this.prob = Double.valueOf(params.get("prob")) / 100.0;
			this.remote = Location.build(params.get("host"), Integer
					.valueOf(params.get("port")));
			
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}

		if (this.meaninterval < 0) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}

		initialize();
	}

	private void initialize() {
		Timer timer = new Timer();
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				timesup = true;
			}
		};
		timer.schedule(tt, AgentUtil.expTime);
		
//		Timer timer1 = new Timer();
//		TimerTask tt1 = new TimerTask() {
//			Runtime r = Runtime.getRuntime();
//			@Override
//			public void run() {
//				if (!timesup || icount == 0) {
//					LOG.info("Read Count " + agentName + " " + type + ":"
//							+ (opCountL + opCountR));
//					LOG.info(agentName
//							+ " -> Total memory: " + r.totalMemory()
//							+ "Used memory: " + (r.totalMemory() - r.freeMemory()));
//				}
//				if (timesup)
//					icount = 1;
//			}
//		};

//		timer1.schedule(tt1, DracoConstants.ADAPTATION_PERIOD,
//				DracoConstants.ADAPTATION_PERIOD);

		dts = DracoTS.get("testing");
		ListReaction lr = new ListReaction(this);
		dts.addStrongReaction(new ListReaction[] { lr });
	}


	@Override
	public void run() {
		super.run();

		sleepWait(AgentUtil.sleepTime);

		while (!timesup && getUnRead().size() == 0) {
			rest(0);
		}
		System.out.println(this.agentName + " start working....");
		while (!timesup) {
			try {
				TupleID id = generateID();

				ShareTuple temp = ShareTuple.createVIDTemplate(id);
				temp.setCurr(remote);
//				System.out.println(Thread.currentThread().getName()
//						+ "is ready to read" + id);
				long begin = System.nanoTime();

				ShareTuple dt = null;

				try {
					dt = (ShareTuple) dts.rdp(temp);
				} catch (Exception ex) {
					System.out.println(Util.getExceptionDetail(ex));
				}

				long curoptime = System.nanoTime() - begin;
				boolean isLocalOp = dt.getCurr().isHere();
				if (isLocalOp) {
					usedTotalTimeL += curoptime;
					opCountL++;
				} else {
					usedTotalTimeR += curoptime;
					opCountR++;
				}
				if (dt != null) {
					LOG.info(String.format(
											"READ,%s,vid=%s,replica=%b,localop=%b,size=%d,"
													+ "version=%d,optime=%g,policy=%s",
											agentName,
											dt.getVID(),
											dt.isReplica(),
											isLocalOp,
											AbstractAgent
													.retriveDataSizeInTuple((FlatShareTuple) dt),
											dt.getVer(),
											curoptime / 1000000000.0, dts
													.getPolicyRegistrar()
													.getReplicaPolicy(
															dt.getType(),
															Location.HERE)));
				} else {
					LOG.info(String.format("READ,%s,FAIL,vid=%s", agentName, id
							.toString()));
				}

				rest(curoptime / 1000000);
			} catch (Exception ex) {
				System.out.println(Util.getExceptionDetail(ex));
			}
		}
		double timePerOpR = usedTotalTimeR / 1000000000.0 / opCountR;
		double timePerOpL = usedTotalTimeL / 1000000000.0 / opCountL;
		String msg = String.format("DONE,%s,optimeR=%g,optimeL=%g,opcountR=%d,opcountL=%d,opcount=%d",
				agentName,
				timePerOpR,
				timePerOpL,
				opCountR,
				opCountL,
				(opCountR + opCountL)
				);
		LOG.info(msg);
		AgentServer.done();
	}

	

	private RandomData randomGet1 = new RandomDataImpl();
	private RandomData randomProb = new RandomDataImpl();
	private RandomData randomGet2 = new RandomDataImpl();

	private TupleID generateID() {
		TupleID tid = null;
		double random = randomProb.nextUniform(0, 1);

		synchronized (unRead) {
			if ((random >= 1 - prob && unRead.size() > 0)
					|| haveRead.size() == 0) {
				tid = (TupleID) randomGet1.nextSample(unRead, 1)[0];
				unRead.remove(tid);
				haveRead.add(tid);
			} else if (haveRead.size() > 0) {
				tid = (TupleID) randomGet2.nextSample(haveRead, 1)[0];
			}
		}
		return tid;
	}

	private HashSet getUnRead() {
		synchronized (unRead) {
			return unRead;
		}
	}

	@Override
	public TupleType getType() {
		return type;
	}

	@Override
	public void updateList(ListTuple lt) {
		synchronized (unRead) {
			unRead.addAll(lt.getTupleList());
		}
	}

	@Override
	public Location getTargetLocation() {
		return remote;
	}
}
